package com.atguigu.datastream.day05;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

/**
 * ClassName: Flink02_CountWindow
 * Package: com.atguigu.day05
 * Description:
 *             计数窗口
 * @Author ChenJun
 * @Create 2023/4/11 16:24
 * @Version 1.0
 */
public class Flink02_CountWindow {
    public static void main(String[] args) throws Exception {

        //1 创建流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        // TODO 将读取的数据转为javaBean
        SingleOutputStreamOperator<WaterSensor> streamOperator = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String s) throws Exception {
                String[] split = s.split(",");

                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        // 3 将相同的key放到一组
        KeyedStream<WaterSensor, String> keyedStream = streamOperator.keyBy(r -> r.getId());

        // TODO 开启一个窗口大小为5 的计数滚动窗口
//        WindowedStream<WaterSensor, String, GlobalWindow> windowedStream = keyedStream.countWindow(5);

        // TODO 开启一个窗口大小为5 ，滑动步长为我 的滑动窗口
        WindowedStream<WaterSensor, String, GlobalWindow> windowedStream = keyedStream.countWindow(5, 2);

        windowedStream.sum("vc").print();

        env.execute();
    }
}
